package com.chixing.day15_map_file.work;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.CellType;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FileExcel {
    public static void main(String[] args) {
        List<Student> list = new ArrayList<>();
        File file = new File("E:\\test2\\student1.xls");
        try {
            FileInputStream fis = new FileInputStream(file);
            POIFSFileSystem fs = new POIFSFileSystem(fis);
            HSSFWorkbook hwb = new HSSFWorkbook(fs);
            HSSFSheet sheet = hwb.getSheet("Sheet1");
            if (sheet==null){
                System.out.println("没有表");
                return;
            }
            System.out.println(sheet.getFirstRowNum());//行和列都是从0开始计数  此处应该为1

            HSSFRow titleRow = sheet.getRow(sheet.getFirstRowNum());//获取标题行

            Map<String,Integer> map = new HashMap<>();
            System.out.println(titleRow.getLastCellNum());//列数最后一列
            for (int i=titleRow.getFirstCellNum();i<titleRow.getLastCellNum();i++){
                map.put(titleRow.getCell(i).getStringCellValue(),i);
            }

            for (int i = sheet.getFirstRowNum()+1;i<=sheet.getLastRowNum();i++){
                HSSFRow dataRow = sheet.getRow(i);
                Student stu = new Student();

                for (String item: map.keySet()){
                    HSSFCell dataCell  = dataRow.getCell(map.get(item));
                    if ("学号".equals(item)){
                        stu.setStuId((int) dataCell.getNumericCellValue());
                    } else if ("姓名".equals(item)) {
                        stu.setStuName(dataCell.getStringCellValue());
                    }else if ("性别".equals(item)) {
                        stu.setStuGender(dataCell.getStringCellValue());
                    }else if ("专业".equals(item)) {
                        stu.setStuMajor(dataCell.getStringCellValue());
                    }else if ("生日".equals(item)) {
                        stu.setStuBirthday(dataCell.getDateCellValue());
                    }
                }
                list.add(stu);
            }
            System.out.println(list);



        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
